<script setup lang="ts">
import { uploadImg } from '@/services/consult'
import type { Image } from '@/types/consult'
import { showLoadingToast, showSuccessToast } from 'vant'
import type { UploaderAfterRead } from 'vant/lib/uploader/types'
import { ref } from 'vue'

defineProps<{
  disabled: boolean
}>()

// 父组件接收 当前输入框的文字
const emit = defineEmits<{
  (e: 'send-text', text: string): void
  (e: 'send-image', img: Image): void
}>()
const text = ref('')
const sendText = () => {
  emit('send-text', text.value)
  // 点击之后,清空输入框的文字
  text.value = ''
}

// 父组件接收 当前上传的图片
const sendImage: UploaderAfterRead = async (data) => {
  // 多张图片是数组对象,但是此次需要单张图片需要对象
  if (Array.isArray(data)) return
  if (!data.file) return // 排除取消选择图片的情况
  showLoadingToast('正在上传图片...')
  const res = await uploadImg(data.file)
  showSuccessToast('图片上传成功了!')
  emit('send-image', res.data) // 拿到返回的图片数据,传递给父组件
}

// Field输入框自动聚焦
</script>

<template>
  <div class="room-action">
    <van-field
      v-model="text"
      :disabled="disabled"
      type="text"
      class="input"
      :border="false"
      placeholder="问医生"
      autocomplete="off"
      @keyup.enter="sendText"
    ></van-field>
    <van-uploader
      :disabled="disabled"
      :preview-image="false"
      :after-read="sendImage"
    >
      <cp-icon name="consult-img"></cp-icon>
    </van-uploader>
  </div>
</template>

<style lang="scss" scoped>
.room-action {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 1;
  box-sizing: border-box;
  .input {
    background-color: var(--cp-bg);
    border: none;
    border-radius: 25px;
    margin-right: 10px;
    padding: 8px 15px;
  }
  .cp-icon {
    width: 24px;
    height: 24px;
  }
}
</style>
